<?php
date_default_timezone_set('Asia/Bangkok');

define( 'DS'	, DIRECTORY_SEPARATOR );
define( 'BASE' 	, __DIR__ . DS . '..' . DS . 'app');

try {
	
	// Read the configuration
	$config = new Phalcon\Config\Adapter\Ini(BASE . DS . 'config' . DS . 'config.ini');

	//Register an autoloader
	$loader = new \Phalcon\Loader();
	$loader->registerDirs(
		array(
			BASE . DS . $config->application->controllersDir . DS,
			BASE . DS . $config->application->modelsDir . DS,
		)
	)->register();

	//Create a DI
	$di = new Phalcon\DI\FactoryDefault();
	
	/**
	 * We register the events manager
	 */
	$di->set('dispatcher', function() use ($di) {
	
		$eventsManager = $di->getShared('eventsManager');
	
		$dispatcher = new Phalcon\Mvc\Dispatcher();
		$dispatcher->setEventsManager($eventsManager);
	
		return $dispatcher;
	});
	
	/**
	 * The URL component is used to generate all kind of urls in the application
	*/
	$di->set('url', function() use ($config){
		$url = new \Phalcon\Mvc\Url();
		$url->setBaseUri($config->application->baseUri);
		return $url;
	});

	//Setting up the view component
	$di->set('view', function() use ($config) {
		$view = new \Phalcon\Mvc\View();
		$view->setViewsDir(BASE . DS . $config->application->viewsDir . DS);
		$view->registerEngines(array(
			".volt" => 'volt'
		));

		return $view;
	});
	
	// Setting up volt
	$di->set('volt', function($view, $di) {
		$volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
		$volt->setOptions(array(
				"compiledPath" => "../cache/volt/"
		));
	
		return $volt;
	}, true);
	
	// Setting Database
	$di->set('db', function() use ($config) {
		return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
			"host" => $config->database->host,
			"username" => $config->database->username,
			"password" => $config->database->password,
			"dbname" => $config->database->name
		));
	});

	//Handle the request
	$application = new \Phalcon\Mvc\Application($di);

	echo $application->handle()->getContent();

} catch(\Phalcon\Exception $e) {
	echo "PhalconException: ", $e->getMessage();
}